/*
 * Copyright (C) 2011  Daniel Léonard
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */

package ca.forklabs.soap.axis.client;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
import java.security.AccessController;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.util.Locale;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;
import java.util.ResourceBundle.Control;

import java.io.IOException;


/**
 * Stripped down version of the true {@code CharsetPropertiesControl} from the
 * <a href="http://code.google.com/p/forklabs-baselib/">forklabs-baselib</a>
 * library.
 *
 * @author   <a href="mailto:forklabs at gmail.com?subject=ca.forklabs.soap.axis.client.CharsetPropertiesControl">Daniel Léonard</a>
 * @version $Revision$
 */
class CharsetPropertiesControl extends ResourceBundle.Control {

//---------------------------
// Class variables
//---------------------------

   /** A predefined instance for resources stored in UTF-8 encoded properties files. */
   public static final CharsetPropertiesControl UTF_8_CONTROL = new CharsetPropertiesControl(Charset.forName("UTF-8")); //$NON-NLS-1$


//---------------------------
// Instance variables
//---------------------------

   /** The charset. */
   private Charset charset;


//---------------------------
// Constructors
//---------------------------

   /**
    * Constructor.
    * @param   charset   the charset.
    */
   public CharsetPropertiesControl(Charset charset) {
      this.setCharset(charset);
      }



//---------------------------
// Accessors and mutators
//---------------------------

   /**
    * Changes the charset.
    * @param   charset   the new charset.
    */
   protected void setCharset(Charset charset) {
      this.charset = charset;
      }

   /**
    * Gets the charset.
    * @return   the charset.
    */
   public Charset getCharset() {
      return this.charset;
      }


//---------------------------
// Overridden methods from java.util.ResourceBundle$Control
//---------------------------

   /**
    * {@inheritDoc}
    */
   @Override
   @SuppressWarnings("hiding")
   public ResourceBundle newBundle(String baseName, Locale locale, String format, ClassLoader loader, boolean reload) throws IllegalAccessException, InstantiationException, IOException {
      ResourceBundle bundle = null;

      boolean is_properties_format = Control.FORMAT_PROPERTIES.contains(format);
   // quick escape here
      if (false == is_properties_format) {
         bundle = super.newBundle(baseName, locale, format, loader, reload);
         }
      else {
         InputStream stream = null;
         try {
            String bundleName = this.toBundleName(baseName, locale);
            final String resourceName = this.toResourceName(bundleName, "properties"); //$NON-NLS-1$
            final ClassLoader classLoader = loader;
            final boolean reloadFlag = reload;

            stream = AccessController.doPrivileged(new PrivilegedExceptionAction<InputStream>() {
               @Override
               @SuppressWarnings("resource")
               public InputStream run() throws IOException {
                  InputStream is = null;
                  if (reloadFlag) {
                     URL url = classLoader.getResource(resourceName);
                     if (url != null) {
                        URLConnection connection = url.openConnection();
                        if (connection != null) {
                        // Disable caches to get fresh data for reloading.
                           connection.setUseCaches(false);
                           is = connection.getInputStream();
                           }
                        }
                     }
                  else {
                     is = classLoader.getResourceAsStream(resourceName);
                     }
                  return is;
                  }
               });
            }
         catch (PrivilegedActionException pae) {
            IOException ioe = (IOException) pae.getException();
            throw ioe;
            }
         if (stream != null) {
            Charset charset = this.getCharset();
            try (Reader reader = new InputStreamReader(stream, charset)){
               bundle = new PropertyResourceBundle(reader);
               }
            }
         }
      return bundle;
      }

   }
